package com.kuang.forkjoin;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 测试求和计算，使用一般方式、ForkJoin、Stream并行流，对比效果
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1();
        test2();   // forkJoin好像没有什么时间提高
        //test3();
    }

    // 一般方式  sum=500000000500000000，耗时：5533
    public static void test1(){
        Long sum = 0L;
        long startTime = System.currentTimeMillis();
        for (long i = 1L; i <= 10_0000_0000L; i++) {
            sum += i;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("sum=" + sum + "，耗时：" + (endTime - startTime));
    }

    // ForkJoin方式 sum=500000000500000000，耗时：10677
    public static void test2() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        // 1.创建分支合并池
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        // 2.创建分支合并任务
        ForkJoinTask<Long> task = new ForkJoinDemo(1L,10_0000_0001L); //[,)
        // 3.提交任务
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        // 4.获取结果
        long sum = submit.get();
        long endTime = System.currentTimeMillis();
        System.out.println("sum=" + sum + "，耗时：" + (endTime - startTime));
    }


    // Stream流方式  sum=500000000500000000，耗时：165
    public static void test3() throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        // 并行流计算，最快
        Long sum = LongStream.rangeClosed(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
        long endTime = System.currentTimeMillis();
        System.out.println("sum=" + sum + "，耗时：" + (endTime - startTime));
    }

}
